package com.hzc.springchan.command.verlocitygeneric.impl;

import com.hzc.springchan.bean.exception.CException;
import com.hzc.springchan.command.verlocitygeneric.IGenericCommand;
import com.hzc.springchan.config.velocity.VelocityConfig;
import com.hzc.springchan.constant.System;
import com.hzc.springchan.enums.PrivError;
import com.hzc.springchan.util.LogUtils;
import com.hzc.springchan.util.SpringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

/**
 * Mapper XML文件生成命令实现类
 * @author chen990627
 * @date 2022/10/13
 */
@Service(System.GenericCommandBean.MAPPER_XML)
@ConditionalOnBean(VelocityConfig.class)
public class MapperXmlGenericCommandImpl implements IGenericCommand {

    private Template template;
    private VelocityContext context;

    @Override
    public Template initTemplate() {

        if (template == null) {
            synchronized (this) {
                if (template == null) {
                    template = SpringUtils.getBean(System.VelocityBean.MAPPER_XML_TEMPLATE, Template.class);
                }
            }
        }
        return template;
    }

    @Override
    public PrintWriter initWriter(String className) {
        PrintWriter writer;
        try {
            writer = new PrintWriter(
                    new File("src/main/resources/mapper/" + className + "Mapper.xml")
            );
        } catch (FileNotFoundException e) {
            LogUtils.error( "文件输出位置不存在：{}", e.toString());
            throw new CException(PrivError.DIRECTORY_NOT_FOUND);
        }
        return writer;
    }

    @Override
    public VelocityContext initContext() {

        if (context == null) {
            synchronized (this) {
                if (context == null) {
                    context = SpringUtils.getBean(VelocityContext.class);
                }
            }
        }
        return context;
    }

    @Override
    public void afterReturn() {
        LogUtils.info(this, "Mapper Xml配置文件生成成功");
    }
}
